package com.boot.message.netty.server.handler.impl;

import com.boot.message.netty.server.handler.BaseServerHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @date 2020/3/14 18:58
 **/
@Slf4j
@ChannelHandler.Sharable
public class JSONServerHandler extends BaseServerHandler {

    private ObjectMapper om;
    private Class<?> clazz;

    public JSONServerHandler(ObjectMapper om, Class<?> clazz) {
        this.om = om;
        this.clazz = clazz;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接成功");
        super.channelActive(ctx);
    }

    @Override
    @SuppressWarnings("all")
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            System.out.println("from client : " + msg);
            if ("exit".equals(msg)) {
                ctx.close();
            } else {
                handle(om.readValue((String) msg, clazz));
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    public void handle(Object o) {
        System.out.println(o);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("连接出错,连接已断开");
        ctx.close();
    }


}